<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

if (!function_exists('delete_dir_file')) {
	/**
	 * 循环删除目录和文件
	 * @param string $dir_name
	 * @return bool
	 */
	function delete_dir_file($dir_name) {
	  	$result = false;
	  	if(is_dir($dir_name)){
	    	if ($handle = opendir($dir_name)) {
	      		while (false !== ($item = readdir($handle))) {
	        		if ($item != '.' && $item != '..') {
	          			if (is_dir($dir_name . DIRECTORY_SEPARATOR . $item)) {
	            			delete_dir_file($dir_name . DIRECTORY_SEPARATOR . $item);
	          			} else {
	            			unlink($dir_name . DIRECTORY_SEPARATOR . $item);
	          			}
	        		}
	      		}
	      		closedir($handle);
	      		if (rmdir($dir_name)) {
	        		$result = true;
	      		}
	    	}
	  	}
	  	return $result;
	}
}

if (!function_exists('path_deal_with')) {
    /**
     * @todo 路径处理
     * @param $id
     * @return mixed|string
     */
    function path_deal_with($path = '')
    {
        if (!preg_match("/^http(s)?:\\/\\/.+/", $path)) {
            if (is_https()) {
                return 'https://'.$_SERVER['HTTP_HOST'] . $path;
            } else {
                return 'http://'.$_SERVER['HTTP_HOST'] . $path;
            }
        } else {
            return $path;
        }
    }
}

if (!function_exists('is_https')) {
    /**
     * Author：Domino
     * Date: 2019/10/15
     * Time: 11:51
     * @todo 判断是不是https
     * @return bool
     */
    function is_https()
    {
        if(!isset($_SERVER['HTTPS']))  return FALSE;
        if($_SERVER['HTTPS'] === 1){  //Apache
            return TRUE;
        }elseif($_SERVER['HTTPS'] === 'on'){ //IIS
            return TRUE;
        }elseif($_SERVER['SERVER_PORT'] == 443){ //其他
            return TRUE;
        }
        return FALSE;
    }
}

if (!function_exists('rich_text_format')) {
    /**
     * @title 替换富文本中的图片路径
     * @param $content
     * @return string|string[]|null
     */
    function rich_text_format($content)
    {
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $list = preg_replace($pregRule, '<img src="' . path_deal_with('${1}') .'" style="max-width:100%">', $content);
        return $list;
    }
}

if (!function_exists('hywx_random')) {
    /**
     * @param int $length
     * @param int $numeric
     * @return string
     * @todo hywx_random() 函数返回随机整数。
     */
    function hywx_random($length = 4, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
}

if (!function_exists('build_order_no')) {
    /**
     * 创建订单号
     */
    function build_order_no($table)
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[rand(0, 9)] . strtoupper(dechex(date('m'))) . date('d') . sprintf('%02d', rand(1000, 9999)) . substr(microtime(), 2, 5) . sprintf('%02d', rand(1000, 9999));
        //检测是否存在
        $info = \think\Db::name($table)->where(['order_no'=>$orderSn])->find();
        if (!empty($info)) {
            build_order_no();
        }
        return $orderSn;
    }
}


if (!function_exists('upload_image')) {
    /**
     * @param file $file 选择的文件
     * @param string $event 事件
     */
    function upload_image($file, $event = 'image')
    {
        $savePath = './uploads/'.$event.'/' . date("Ymd") . "/";
        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true);
        }
        $info = $file->rule('uniqid')->validate(['ext' => 'jpg,png,jpeg'])->move($savePath);
        if ($info) {
            $fileName = $info->getFilename();
            $filePath = str_replace("./", "/", $savePath . $fileName);
            // 图像缩略图
            $resize = [];
            switch ($event) {
                case 'avatar':
                    $resize[] = [120, 120];
                    break;
                default:
                    // $resize[] = [200, 200];
                    break;
            }
            create_thumb($filePath, $resize);
            return $filePath;
        }
        return '';
    }
}

if (!function_exists('create_thumb')) {
    /**
     * 创建缩略图
     * @param string $filePath 目标文件，可以是文件对象或文件路径
     * @param string $resize 尺寸
     * @return string 缩略图路径
     * @author eric
     */
    function create_thumb($filePath = '', $resize = '')
    {
        $file = explode('/', $filePath);
        $fileDate = $file[count($file) - 3] . '/' . $file[count($file) - 2];
        $file = explode('.', $file[count($file) - 1]);
        $fileName = $file[0];
        $fileExt = $file[1];
        $thumb_path_name = '';
        foreach ($resize as $thumb_size) {
            // 获取要生成的缩略图最大宽度和高度
            list($thumb_max_width, $thumb_max_height) = $thumb_size;
            // 读取图片
            $image = \think\Image::open(env('root_path') . '/public/' . $filePath);
            // 生成缩略图
            $image->thumb($thumb_max_width, $thumb_max_height, 1);
            // 保存缩略图
            $thumb_path = env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $fileDate;
            $newImageName = $fileName . '_' . $thumb_max_width . 'x' . $thumb_max_height . '.' . $fileExt;
            $thumb_path_name = $thumb_path . DIRECTORY_SEPARATOR . $newImageName;
            $image->save($thumb_path_name);
        }
        return $thumb_path_name;
    }
}

if (!function_exists('get_thumb_img')) {
    /**
     * @param $file 数据库存储原图地址
     * @param $width  缩略图宽带
     * @param $height 缩略图高度
     * @return array
     */
    function get_thumb_img($file, $width, $height, $host = false, $str = false)
    {
        $files = is_array($file) ? $file : explode(',', $file);
        $data = [];
        if (!$height) {
            $height = $width;
        }
        foreach ($files as $item) {
            $img = explode('.', $item);
            if (!empty($img) && !is_null($img) && $img[0] != '' && $img[1] != '') {
                $thumb_img = $img[0] . '_' . $width . 'x' . $height . '.' . $img[1];
                if (!file_exists(env('root_path') . 'public' . $thumb_img)) {
                    $thumb_img = $item;
                }
            } else {
                $thumb_img = $item;
            }
            $data[] = $host ? path_deal_with($thumb_img) : $thumb_img;
        }
        return $str ? implode(',', $data) : $data;
    }
}

if (!function_exists('format_time')) {

    /**
     * 将时间转换为 几小时前 的格式
     * @param  string $date  时间
     * @return string
     */
    function format_time($date) {
        $str = '';
        $timer = is_numeric($date) ? $date : strtotime($date);
        $diff = $_SERVER['REQUEST_TIME'] - $timer;
        $day = floor($diff / 86400);
        $free = $diff % 86400;
        if($day > 0) {
            return $day."天前";
        }else{
            if($free>0){
                $hour = floor($free / 3600);
                $free = $free % 3600;
                if($hour>0){
                    return $hour."小时前";
                }else{
                    if($free>0){
                        $min = floor($free / 60);
                        $free = $free % 60;
                        if($min>0){
                            return $min."分钟前";
                        }else{
                            if($free>0){
                                return $free."秒前";
                            }else{
                                return '刚刚';
                            }
                        }
                    }else{
                        return '刚刚';
                    }
                }
            }else{
                return '刚刚';
            }
        }
    }
}